# -*- coding:utf-8 -*-
class Temperature(object):
    converts = {'f':(-273.5,1.8,32),'c':(0,1,-273.5)} # k:开氏度 f:华氏度 c:摄氏度 程序内部以k为标准 f = (k+(-273.5)) * 1.8 + 32  c = (k + 0)*1+(-273.5)

    def __init__(self , **kwargs):
        # 程序默认温度是绝对零度(k = 0),可以传入一个参数作为初始温度
        try:
            name , value = kwargs.popitem()
        except KeyError:
            # 默认参数 k = 0
            name , value = 'k' , 0
        if kwargs or name not in 'fc':
            kwargs[name] = value # 调试用
            raise TypeError , 'invalid arguments %s' % kwargs
        setattr(self,name,float(value))
    
    def __getattr__(self,name):
        try:
            # eq = self.converts[name] #important 当实例对象中不存在变量converts时 会去变量中查找 . 为了可读性最好还是使用 Class_name.variable
            eq = Temperature.converts[name]
        except KeyError:
            raise AttributeError , name
        return (self.k+eq[0]) * eq[1] + eq[2]

    def __setattr__(self,name,value):
        # if name in self.converts:
        if name in Temperature.converts:
            # eq = self.converts[name]
            eq = Temperature.converts[name]
            self.k = (value-eq[2]) / eq[1] - eq[0]
        elif name == 'k':
            object.__setattr__(self,name,value)
        else:
            raise AttributeError,name
    
    def __str__(self):
        return '%s K' % self.k

    def __repr__(self):
        return 'Temperatur(k=%s)' % self.k

if __name__ == '__main__':
    t = Temperature(c=40)
    print t.f #104
    print t
    t.f = 100
    print '%s F' % t.f # output 100
    print '%s C' % t.c # output 37
    print t # output 311

# 学习 讲解 分而治之 最后总结
